package vn.com.hung.notetaker.utils;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Enumeration;
import java.util.Stack;
import java.util.logging.Logger;

import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTML.Attribute;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.parser.ParserDelegator;

public class HTML2Text extends HTMLEditorKit.ParserCallback {
    private static final Logger log = Logger
            .getLogger(Logger.GLOBAL_LOGGER_NAME);

    private StringBuffer stringBuffer;

    private Stack<IndexType> indentStack;

    public static class IndexType {
        public String type;
        public int counter; // used for ordered lists

        public IndexType(String type) {
            this.type = type;
            counter = 0;
        }
    }

    public HTML2Text() {
        stringBuffer = new StringBuffer();
        stringBuffer.append("<html>\n");
        indentStack = new Stack<IndexType>();
    }

    public static String convert(String html) {
        HTML2Text parser = new HTML2Text();
        Reader in = new StringReader(html);
        try {
            // the HTML to convert
            parser.parse(in);
        } catch (Exception e) {
            log.severe(e.getMessage());
        } finally {
            try {
                in.close();
            } catch (IOException ioe) {
                // this should never happen
            }
        }
        
        return parser.getText();
    }

    public void parse(Reader in) throws IOException {
        ParserDelegator delegator = new ParserDelegator();
        // the third parameter is TRUE to ignore charset directive
        delegator.parse(in, this, Boolean.TRUE);
    }
    
    @Override
    public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {
        log.info("StartTag:" + t.toString());
        if (t.toString().equals("p")) {
            if (stringBuffer.length() > 0
                    && !stringBuffer.substring(stringBuffer.length() - 1)
                            .equals("\n")) {
                newLine("<p>");
            }
            newLine("<p>");
        } else if (t.toString().equals("ol")) {
            indentStack.push(new IndexType("ol"));
            newLine("<ol>");
        } else if (t.toString().equals("ul")) {
            indentStack.push(new IndexType("ul"));
            newLine("<ul>");
        } else if (t.toString().equals("li")) {
            IndexType parent = indentStack.peek();
            if (parent.type.equals("ol")) {
                String numberString = "" + (++parent.counter) + ".";
                stringBuffer.append("<li>");
                //stringBuffer.append(numberString);
                for (int i = 0; i < (4 - numberString.length()); i++) {
                    stringBuffer.append(" ");
                }
            } else {
                stringBuffer.append("*   ");
            }
            indentStack.push(new IndexType("li"));
        } else if (t.toString().equals("dl")) {
            newLine("</dl>");
        } else if (t.toString().equals("dt")) {
            newLine("</dt>");
        } else if (t.toString().equals("dd")) {
            indentStack.push(new IndexType("dd"));
            newLine("</dd>");
        } else if (t.toString().equals("font")) {
           Enumeration<Attribute> e = (Enumeration<Attribute>) a.getAttributeNames();
           stringBuffer.append("<font");
           while (e.hasMoreElements()) {
               Attribute at = e.nextElement();
               stringBuffer.append(" " + at.toString() + "=" + a.getAttribute(at));
               //System.out.println(at);
               //System.out.println(a.getAttribute(at));
           }
           stringBuffer.append(" >");
        }
    }


    private void newLine(String tag) {
        stringBuffer.append(tag + "\n");
        for (int i = 0; i < indentStack.size(); i++) {
            stringBuffer.append("    ");
        }
    }
    
    @Override
    public void handleEndTag(HTML.Tag t, int pos) {
        log.info("EndTag:" + t.toString());
        if (t.toString().equals("p")) {
            newLine("</p>");
        } else if (t.toString().equals("ol")) {
            indentStack.pop();
            newLine("</ol>");
        } else if (t.toString().equals("ul")) {
            indentStack.pop();
            newLine("</ul>");
        } else if (t.toString().equals("li")) {
            indentStack.pop();
            newLine("</li>");
        } else if (t.toString().equals("dd")) {
            indentStack.pop();
            
        } else if (t.toString().equals("font")) {
            stringBuffer.append("</font>");
        }
    }

    public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) {
        log.info("SimpleTag:" + t.toString());
        if (t.toString().equals("br")) {
            newLine("<br>");
        }
    }

    public void handleText(char[] text, int pos) {
        log.info("Text:" + new String(text));
        stringBuffer.append(text);
    }

    public String getText() {
        stringBuffer.append("</html>");
        return stringBuffer.toString();
    }

    public static void main(String args[]) {
        String html = getSampleContent();
        System.out.println(convert(html));
    }
    
    public static String getSampleContent() {
        return "<html> <p> Contains extensions to the Swing GUI toolkit, including new and enhanced components that provide functionality commonly required by rich client applications. Highlights include: </p>"
                + "<ol> <li>Sorting, filtering, highlighting for tables, trees, and lists </li>"
                + "<li>Find/search</li>"
                + "<li>Auto-completion</li>"
                + "<li>Login/authentication framework</li>"
                + "<li>TreeTable component</li>"
                + "<li>Collapsible panel component</li>"
                + "<li>Date picker <font color = \"red\">component</font></li>"
                + "<li>Tip-of-the-Day component</li> "
                + "</ol> <p>"
                + "Many of these features will eventually be incorporated into the Swing toolkit, although API compatibility will not be guaranteed. The SwingX project focuses exclusively on the raw components themselves"
                + "</p> </html>";
    }
}
